package com.smartstate.autoMaticControl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.smartstate.common.feign.client.AuthorityClient;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

@Component
@Slf4j
public class FeignRequestInterceptorConfig implements RequestInterceptor {

    private final String AUTHORIZATION_HEADER = "Authorization";

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private AuthorityClient authorityClient;
    /**
     * 添加token
     */
    public final String FROM_IN = "Y";

    /**
     * 标志
     */
    public final String FROM = "from";

    @Value("${security.oauth2.client.client-id}")
    private String clientId;

    @Value("${security.oauth2.client.client-secret}")
    private String clientSecret;


    /**
     * 1. 如果使用 非web 请求，header 区别
     * 2. 根据authentication 还原请求token
     * 3.查看是否有内部调用标志
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        Collection<String> fromHeader = template.headers().get(FROM);
        if (CollUtil.isNotEmpty(fromHeader) && fromHeader.contains(FROM_IN)) {
            JSONObject result = authorityClient.oauthToken(clientId,clientSecret, "client_crodentials", "all",null, null);
            template.header(AUTHORIZATION_HEADER, "Bearer " +  result.get("access_token"));
            return;
        }
    }
}